package com.example.mapprogram;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;

import java.util.List;

import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;


public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener, WeatherSearch.OnWeatherSearchListener {

    MapView mMapView = null;

    //初始化地图控制器对象
    AMap aMap;


    //定位需要的数据
    OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;

    //定位蓝点
    MyLocationStyle myLocationStyle;
    //ACCESS_COARSE_LOCATION


    //TODO 创建地理围栏对象
    //实例化地理围栏客户端
    GeoFenceClient mGeoFenceClient = null;
    //创建回调监听
    GeoFenceListener fenceListenter = new GeoFenceListener() {

        @Override
        public void onGeoFenceCreateFinished(List<GeoFence> list, int errorCode, String s) {
            if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {//判断围栏是否创建成功
                //tvReult.setText("添加围栏成功!!");
                Toast.makeText(MainActivity.this, "添加围栏成功!!", Toast.LENGTH_SHORT).show();
                //geoFenceList是已经添加的围栏列表，可据此查看创建的围栏
            } else {
                //tvReult.setText("添加围栏失败!!");
                Toast.makeText(MainActivity.this, "添加围栏失败!!!!", Toast.LENGTH_SHORT).show();

            }

        }


    };

    //定义接收广播的action字符串
    public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
    private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                //解析广播内容
//获取Bundle
                Bundle bundle = intent.getExtras();
//获取围栏行为：
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
//获取自定义的围栏标识：
                String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
//获取围栏ID:
                String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
//获取当前有触发的围栏对象：
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                if (fence.getStatus()==fence.STATUS_IN) {
                    Toast.makeText(context, "你已在打卡范围内", Toast.LENGTH_SHORT).show();

                } else if (fence.getStatus()==fence.STATUS_OUT){
                    Toast.makeText(context, "你不在打开范围内", Toast.LENGTH_SHORT).show();

                }
            }
        }
    };
    private WeatherSearchQuery mquery;
    private WeatherSearch mweathersearch;
    private TextView wheaher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        wheaher=findViewById(R.id.wheather);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //设置地图的放缩级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);


        //蓝点初始化
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类

        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。

        myLocationStyle.showMyLocation(true);

        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                //从location对象中获取经纬度信息，地址描述信息，建议拿到位置之后调用逆地理编码接口获取

            }
        });
        //TODO 设置固定点和圆圈⭕
        LatLng latLngs = new LatLng(39.08520610697878, 117.10355999999993);
        /*aMap.addCircle(new CircleOptions().
                center(latLngs).
                radius(200).
                fillColor(Color.argb(0, 1, 1, 1)).
                strokeColor(Color.argb(0, 1, 1, 1)).
                strokeWidth(15));*/
        initGeoFn();
        initWeather();
    }

    private void initWeather() {
        //检索参数为城市和天气类型，实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST
        mquery = new WeatherSearchQuery("北京", WeatherSearchQuery.WEATHER_TYPE_LIVE);
        mweathersearch=new WeatherSearch(this);
        mweathersearch.setOnWeatherSearchListener(this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索
    }

    private void initGeoFn() {
        mGeoFenceClient = new GeoFenceClient(getApplicationContext());
        //设置希望侦测的围栏触发行为，默认只侦测用户进入围栏的行为
        //public static final int GEOFENCE_IN 进入地理围栏
        //public static final int GEOFENCE_OUT 退出地理围栏
        //public static final int GEOFENCE_STAYED 停留在地理围栏内10分钟
        mGeoFenceClient.setActivateAction(GEOFENCE_IN | GEOFENCE_OUT | GEOFENCE_STAYED);

        //TODO 2.0创建地理围栏

        //创建一个中心点坐标
        DPoint centerPoint = new DPoint();
        //设置中心点纬度
        centerPoint.setLatitude(39.078983);
        //设置中心点经度
        centerPoint.setLongitude(117.097048);

        LatLng latLng = new LatLng(39.078983, 117.097048);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("渤海性能科技有限F坐").snippet("DefaultMarker"));


        //执行添加围栏的操作
        // mGeoFenceClient.addGeoFence("F坐","楼房",centerPoint,1000F,10,"000FATE23（考勤打卡）");
        mGeoFenceClient.addGeoFence(centerPoint, 200, "000FATE23（考勤打卡）");
        LatLng latLngss = new LatLng(39.078983, 117.097048);
        //Log.e("精度和卫笃","进度:="+aMapLocation.getLongitude()+"卫笃="+aMapLocation.getLatitude());
        aMap.addCircle(new CircleOptions().
                center(latLngss).
                radius(200).
                fillColor(Color.argb(225, 225, 161, 220)).strokeColor(Color.RED).
                strokeWidth(15));

        mGeoFenceClient.setGeoFenceListener(fenceListenter);//设置回调监听
        //创建并设置PendingIntent
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(GEOFENCE_BROADCAST_ACTION);
        registerReceiver(mGeoFenceReceiver, filter);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    //--定位监听---------

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);

            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }

    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    //定位回调  在回调方法中调用“mListener.onLocationChanged(amapLocation);”可以在地图上显示系统小蓝点。
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                String city=aMapLocation.getCountry()+aMapLocation.getCity()+aMapLocation.getAddress();
                //Toast.makeText(this, "city:"+city, Toast.LENGTH_SHORT).show();
                /*LatLng latLng = new LatLng(39.078983,117.097048);
                Log.e("精度和卫笃","进度:="+aMapLocation.getLongitude()+"卫笃="+aMapLocation.getLatitude());
                aMap.addCircle(new CircleOptions().
                        center(latLng).
                        radius(300).
                        fillColor(Color.argb(225,225,161,220)).strokeColor(Color.RED).
                        strokeWidth(15));*/
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("定位AmapErr", errText);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    /**
     * 实时天气查询回调
     */
    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult ,int rCode) {
        if (rCode == 1000) {
            if (weatherLiveResult != null&&weatherLiveResult.getLiveResult() != null) {
                LocalWeatherLive weatherlive = weatherLiveResult.getLiveResult();
                Toast.makeText(this, weatherlive.getReportTime()+"发布"+weatherlive.getWeather()
                        +weatherlive.getTemperature()+"°"
                        +weatherlive.getWindDirection()+"风     "+weatherlive.getWindPower()+"级"
                        +"湿度         "+weatherlive.getHumidity()+"%"
                        , Toast.LENGTH_SHORT).show();
                wheaher.setText(weatherlive.getReportTime()+"发布"+weatherlive.getWeather()
                        +weatherlive.getTemperature()+"°"
                        +weatherlive.getWindDirection()+"风     "+weatherlive.getWindPower()+"级"
                        +"湿度         "+weatherlive.getHumidity()+"%");

                Log.e("天气",weatherlive.getReportTime()+"发布"+weatherlive.getWeather()
                        +weatherlive.getTemperature()+"°"
                        +weatherlive.getWindDirection()+"风     "+weatherlive.getWindPower()+"级"
                        +"湿度         "+weatherlive.getHumidity()+"%");
            }else {
                Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(this, rCode, Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

    }
}
